//
//  File.swift
//  DemoTest
//
//  Created by 韦小新 on 2022/4/17.
//


import Foundation
import SpriteKit
import SwiftUI

class GameView: SKScene {
    let boy = SKSpriteNode(imageNamed: "boy1")
    var lastUpdateTime: TimeInterval = 0
    var dt: TimeInterval = 0
    let boyMovePointsPerSec: CGFloat = 480.0
    var velocity = CGPoint.zero
    let playableRect: CGRect
    var lastTouchLocation: CGPoint?
    let boyRotateRadiansPerSec:CGFloat = 4.0 * π
    let boyAnimation:SKAction
    let cameraNode = SKCameraNode()
    let cameraMovePointsPerSec: CGFloat = 200.0
    let storyLabel = SKLabelNode(fontNamed: "GLIMSTIC")
    
    override init(size: CGSize) {
      let maxAspectRatio:CGFloat = 16.0/9.0
      let playableHeight = size.width / maxAspectRatio
      let playableMargin = (size.height-playableHeight)/2.0
      playableRect = CGRect(x: 0, y: playableMargin,
                            width: size.width,
                            height: playableHeight)
        boy.size = CGSize(width: 300, height: 300)
      // 1
      var textures:[SKTexture] = []
      // 2
      for i in 1...3 {
        textures.append(SKTexture(imageNamed: "boy\(i)"))
      }
      // 3
      textures.append(textures[2])
      textures.append(textures[1])
      print(textures)
      // 4z
      boyAnimation = SKAction.animate(with: textures,
                                      timePerFrame: 0.1)
    
      super.init(size: size)
    }
   
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func debugDrawPlayableArea() {
      let shape = SKShapeNode()
      let path = CGMutablePath()
      path.addRect(playableRect)
      shape.path = path
//      shape.strokeColor = SKColor.red
      shape.lineWidth = 4.0
      addChild(shape)
    }
    override func didMove(to view: SKView) {
        let background = backgroundNode()
        background.anchorPoint = CGPoint.zero
        background.name = "background"
        background.zPosition = -1
        addChild(background)
      
      boy.position = CGPoint(x: 400, y: 400)
      addChild(boy)
      // zombie.run(SKAction.repeatForever(zombieAnimation))
      
        storyLabel.text = "Now go to take cake"
        storyLabel.fontColor = SKColor.black
        storyLabel.fontSize = 100
        storyLabel.horizontalAlignmentMode = .left
        storyLabel.verticalAlignmentMode = .bottom
        storyLabel.position = CGPoint(x: 0, y: playableRect.size.height/2 - CGFloat(100))
        print("Add success")
        addChild(storyLabel)
                                
    }
    override func update(_ currentTime: TimeInterval) {
    
      if lastUpdateTime > 0 {
        dt = currentTime - lastUpdateTime
      } else {
        dt = 0
      }
      lastUpdateTime = currentTime
    
      if let lastTouchLocation = lastTouchLocation {
        let diff = lastTouchLocation - boy.position
          if diff.length() <= boyMovePointsPerSec * CGFloat(dt) {
          boy.position = lastTouchLocation
          velocity = CGPoint.zero
         stopBoyAnimation()
        } else {
          move(sprite: boy, velocity: velocity)
            print("boy's position = \(boy.position) and zPosition \(boy.zPosition)")
        }
      }
    
      boundsCheckBoy()
      // checkCollisions()
      
    }
    func backgroundNode() -> SKSpriteNode {
      // 1
      let backgroundNode = SKSpriteNode(imageNamed: "CakeShop.jpg")
      backgroundNode.anchorPoint = CGPoint.zero
      backgroundNode.name = "background"
        backgroundNode.size = self.size
        return backgroundNode
    }
    
    
    func move(sprite: SKSpriteNode, velocity: CGPoint) {
      let amountToMove = CGPoint(x: velocity.x * CGFloat(dt),
                                 y: velocity.y * CGFloat(dt))
      sprite.position += amountToMove
    }
    
    func sceneTouched(touchLocation:CGPoint) {
      lastTouchLocation = touchLocation
      moveBoyToward(location: touchLocation)
    }
    
    func moveBoyToward(location: CGPoint) {
      startZombieAnimation()
        let offset = location - boy.position
      let direction = offset.normalized()
      velocity = direction * boyMovePointsPerSec
    }
    
    override func touchesBegan(_ touches: Set<UITouch>,
        with event: UIEvent?) {
      guard let touch = touches.first else {
        return
      }
      let touchLocation = touch.location(in: self)
      sceneTouched(touchLocation: touchLocation)
    }
    
    
    func startZombieAnimation() {
      if boy.action(forKey: "animation") == nil {
        boy.run(
          SKAction.repeatForever(boyAnimation),
          withKey: "animation")
      }
    }
    func stopBoyAnimation() {
      boy.removeAction(forKey: "animation")
    }
    
    func boundsCheckBoy() {
      let bottomLeft = CGPoint(x: 0, y: playableRect.minY)
      let topRight = CGPoint(x: size.width, y: playableRect.maxY)
      
      if boy.position.x <= bottomLeft.x {
        boy.position.x = bottomLeft.x
        velocity.x = -velocity.x
      }
      if boy.position.x >= topRight.x {
        boy.position.x = topRight.x
        velocity.x = -velocity.x
      }
      if boy.position.y <= bottomLeft.y {
        boy.position.y = bottomLeft.y
        velocity.y = -velocity.y
      }
      if boy.position.y >= topRight.y {
        boy.position.y = topRight.y
        velocity.y = -velocity.y
      }
    }
    
    
}



